package com.lianzhihui.minitiktok.ui.main.one

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.jzvd.Jzvd
import com.bytedance.tiktok.utils.OnVideoControllerListener
import com.echofeng.common.ui.base.BaseFragment
import com.echofeng.common.ui.widget.dialog.ShareDialog
import com.echofeng.common.ui.widget.view.LikeView
import com.echofeng.common.ui.widget.view.jzplayer.JzvdStdTikTok
import com.echofeng.common.ui.widget.view.viewpagerlayoutmanager.OnViewPagerListener
import com.echofeng.common.ui.widget.view.viewpagerlayoutmanager.ViewPagerLayoutManager
import com.echofeng.common.utils.RxBus
import com.lianzhihui.minitiktok.adapter.VideoAdapter
import com.lianzhihui.minitiktok.bean.MainPageChangeEvent
import com.lianzhihui.minitiktok.bean.hot.HotClassResponse
import com.lianzhihui.minitiktok.bean.hot.VideoResponse
import com.lianzhihui.minitiktok.bean.test.DataCreate
import com.lianzhihui.minitiktok.presenter.HomePresnterImp
import com.lianzhihui.minitiktok.ui.main.one.PlayListActivity.Companion.initPos
import com.lianzhihui.minitiktok.view.HomeView
import com.lianzhihui.minitiktok.widget.dialog.CommentDialog
import com.lianzhihui.minitiktok.widget.view.ControllerView
import com.lianzhihui.onlyleague.R
import kotlinx.android.synthetic.main.fragment_video_page.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"

/**
 * A simple [Fragment] subclass.
 * Use the [VideoPageFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class VideoPageFragment : BaseFragment(),HomeView,OnViewPagerListener,SwipeRefreshLayout.OnRefreshListener {
    private lateinit var homePresnterImp: HomePresnterImp
    private var adapter: VideoAdapter? = null
    private var viewPagerLayoutManager: ViewPagerLayoutManager? = null
    /** 当前播放视频位置  */
    private val mCurrentPosition = -1

    // TODO: Rename and change types of parameters
    private var isHot: Boolean = false
    companion object {
        @JvmStatic
        fun newInstance(param1: Boolean) =
                VideoPageFragment().apply {
                    arguments = Bundle().apply {
                        putBoolean(ARG_PARAM1, param1)
                    }
                }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            isHot = it.getBoolean(ARG_PARAM1)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_video_page
    }

    override fun initView() {
        refreshLayout!!.setOnRefreshListener(this)
        adapter = VideoAdapter(ArrayList())
        recyclerView!!.adapter = adapter
        viewPagerLayoutManager = ViewPagerLayoutManager(activity)
        recyclerView!!.layoutManager = viewPagerLayoutManager
        recyclerView!!.scrollToPosition(initPos)
        viewPagerLayoutManager!!.setOnViewPagerListener(this)
        recyclerView.addOnChildAttachStateChangeListener(object : OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {}
            override fun onChildViewDetachedFromWindow(view: View) {
                val jzvd: Jzvd = view.findViewById(R.id.videoPlayer)
                if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource != null &&
                        jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.currentUrl)) {
                    if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                        Jzvd.releaseAllVideos()
                    }
                }
            }
        })
    }

    override fun initData() {
        homePresnterImp = HomePresnterImp(context,this)
    }
    override fun onFragmentVisible() {
        super.onFragmentVisible()
        if (!loadFinish){
            if (isHot) {
                homePresnterImp.getRecommendVideo(pageNum)
            }else{
//                homePresnterImp.getm)
            }
            loadFinish = true;
        }
    }
    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }
    override fun onInitComplete() {
        //自动播放第一条
        autoPlayVideo(0)
    }

    override fun onPageRelease(isNext: Boolean, position: Int) {
        if (mCurrentPosition == position) {
            Jzvd.releaseAllVideos()
        }
    }

    override fun onPageSelected(position: Int, isBottom: Boolean) {
        if (mCurrentPosition == position) {
            return
        }
        autoPlayVideo(position)
    }
    private fun autoPlayVideo(position: Int) {
        if (recyclerView == null || recyclerView.getChildAt(0) == null) {
            return
        }
        val player: JzvdStdTikTok = recyclerView.getChildAt(0).findViewById(R.id.videoPlayer)
        if (player != null) {
            player.startVideoAfterPreloading()
        }
        val itemView = viewPagerLayoutManager!!.findViewByPosition(position) ?: return
        val rootView = itemView.findViewById<ViewGroup>(R.id.rl_container)
        val likeView: LikeView = rootView.findViewById(R.id.mLikeView)
        val controllerView: ControllerView = rootView.findViewById(R.id.mControllerView)

        //播放暂停事件
        likeView.setOnPlayPauseListener(object: LikeView.OnPlayPauseListener {
            override fun onPlayOrPause() {
//                if (videoView!!.isPlaying) {
//                    videoView!!.pause()
//                    ivPlay.visibility = View.VISIBLE
//                } else {
//                    videoView!!.start()
//                    ivPlay.visibility = View.GONE
//                }
            }

        })
        //评论点赞事件
        likeShareEvent(controllerView)
    }
    override fun onRefresh() {
        pageNum==1
        homePresnterImp.getRecommendVideo(pageNum)
        object : CountDownTimer(1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {}
            override fun onFinish() {
                refreshLayout!!.isRefreshing = false
            }
        }.start()
    }

    /**
     * 用户操作事件
     */
    private fun likeShareEvent(controllerView: ControllerView) {
        controllerView.setListener(object : OnVideoControllerListener {
            override fun onHeadClick() {
//                EventBus.getDefault().post()
                RxBus.getDefault().post(MainPageChangeEvent(1))
            }

            override fun onLikeClick() {}
            override fun onCommentClick() {
                context?.let { CommentDialog(it).show() }
            }

            override fun onShareClick() {
                context?.let { ShareDialog(it).show() }
            }
        })
    }

    override fun setSuccess(o: Any?) {
    }

    override fun setFailure(o: Any?) {
    }

    override fun setVideoRecommendSuccess(data: MutableList<VideoResponse>?) {
    }

    override fun setSearchVideoSuccess(data: MutableList<VideoResponse>?) {
    }

    override fun setHotClassSuccess(data: MutableList<HotClassResponse>?) {
    }

}
